package com.rm.zeyou.util.string;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 获取本项目所有api接口🤙🤙🏼🤙🏽
 * @date 2024 7月 30 11:21
 * @Description
 */
@Component
public class ControllerUtil {
    @Resource
    private WebApplicationContext webApplicationContext;

    /**
     * 获取所有以/api开头的接口
     * @Date 2024 7月 30 11:22
     * @return api集合
     */
    public List<String> getApiParam() {
        if (webApplicationContext == null) {
            throw new IllegalStateException("webApplicationContext is not initialized.");
        }
        RequestMappingHandlerMapping mapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();

        ArrayList<String> urlList = new ArrayList<>();
        for (RequestMappingInfo info : handlerMethods.keySet()) {
            // 确保每个RequestMappingInfo对象都包含PatternsCondition
            assert info.getPatternsCondition() != null;
            // 获取所有匹配的URL
            Set<String> urlSet = info.getPatternsCondition().getPatterns();
            // 获取所有匹配的请求方法
            Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
            // 打印请求方法
            System.out.println(methods.toString());
            // 使用Stream API筛选出以"/api"开头的URL，并添加到urlList中
            urlList.addAll(urlSet.stream().filter(s -> s.startsWith("/api")).collect(Collectors.toSet()));
        }
        return urlList;
    }
}
